<template>
  <div class="ai-config">
    <div class="config-header">
      <h3>AI 模型配置</h3>
      <button @click="showAddDialog = true" class="btn btn-primary">
        添加新模型
      </button>
    </div>

    <!-- 帮助说明 -->
    <div class="help-section">
      <div class="help-content markdown-content" v-html="renderMarkdown(helpText)"></div>
    </div>

    <!-- 模型列表 -->
    <div class="models-list">
      <div 
        v-for="model in models" 
        :key="model.key"
        :class="['model-item', { 'current': model.is_current }]"
      >
        <div class="model-info">
          <div class="model-name">
            {{ model.name }}
            <span v-if="model.is_current" class="current-badge">当前</span>
          </div>
          <div class="model-provider">{{ getProviderName(model.provider) }}</div>
        </div>
        <div class="model-actions">
          <button 
            v-if="!model.is_current" 
            @click="setCurrentModel(model.key)"
            class="btn btn-secondary btn-sm"
          >
            设为当前
          </button>
          <button @click="editModel(model)" class="btn btn-outline btn-sm">
            编辑
          </button>
          <button 
            @click="deleteModel(model.key)"
            class="btn btn-danger btn-sm"
            :disabled="model.is_current"
          >
            删除
          </button>
        </div>
      </div>
      
      <div v-if="models.length === 0" class="no-models">
        暂无AI模型配置，请添加新模型
      </div>
    </div>

    <!-- 添加/编辑模型对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="config-dialog">
      <div class="dialog-content">
        <h4>{{ showEditDialog ? '编辑模型' : '添加新模型' }}</h4>
        <div class="config-form">
          <div class="form-group">
            <label>模型标识：</label>
            <input 
              v-model="editingModel.key" 
              placeholder="如：qwen、openai等"
              :disabled="showEditDialog"
            >
          </div>
          <div class="form-group">
            <label>模型名称：</label>
            <input v-model="editingModel.name" placeholder="如：通义千问、OpenAI GPT等">
          </div>
          <div class="form-group">
            <label>AI提供商：</label>
            <select v-model="editingModel.provider">
              <option value="local">本地LM Studio</option>
              <option value="qwen">通义千问</option>
              <option value="openai">OpenAI</option>
              <option value="claude">Claude</option>
            </select>
          </div>
          <div class="form-group">
            <label>API密钥：</label>
            <input 
              type="password" 
              v-model="editingModel.api_key" 
              placeholder="输入API密钥"
            >
          </div>
          <div class="form-group">
            <label>模型名称：</label>
            <input v-model="editingModel.model" placeholder="如：qwen-turbo、gpt-3.5-turbo等">
          </div>
          <div class="form-group">
            <label>最大Token数：</label>
            <input 
              type="number" 
              v-model="editingModel.max_tokens" 
              min="-1" 
              max="4000" 
              placeholder="-1表示无限制"
            >
          </div>
          <div class="form-group">
            <label>温度：</label>
            <input 
              type="number" 
              v-model="editingModel.temperature" 
              min="0" 
              max="2" 
              step="0.1"
            >
          </div>
          <div class="form-group">
            <label>API地址：</label>
            <input v-model="editingModel.base_url" placeholder="API地址">
          </div>
        </div>
        <div class="dialog-actions">
          <button @click="saveModel" class="btn btn-primary">
            {{ showEditDialog ? '更新' : '添加' }}
          </button>
          <button @click="closeDialog" class="btn btn-secondary">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { marked } from 'marked'
import { getAIModels, addAIModel, updateAIModel, deleteAIModel, setCurrentAIModel, getAIConfig } from '@/api'

// 响应式数据
const models = ref<Array<{
  key: string
  name: string
  provider: string
  is_current: boolean
}>>([])

const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editingModel = ref({
  key: '',
  name: '',
  provider: 'local',
  api_key: '',
  model: '',
  max_tokens: 2000,
  temperature: 0.7,
  base_url: ''
})

// 帮助文本
const helpText = ref(`
## AI模型配置说明

### 支持的AI提供商

1. **本地LM Studio**
   - 适用于本地部署的大语言模型
   - Base URL: \`http://localhost:1234\`
   - 无需API密钥

2. **通义千问**
   - 阿里云通义千问大模型
   - Base URL: \`https://dashscope.aliyuncs.com/compatible-mode/v1\`
   - 需要API密钥

3. **OpenAI**
   - OpenAI GPT系列模型
   - Base URL: \`https://api.openai.com/v1\`
   - 需要API密钥

4. **Claude**
   - Anthropic Claude模型
   - Base URL: \`https://api.anthropic.com\`
   - 需要API密钥

### 配置说明

- **模型标识**: 用于区分不同模型的唯一标识符
- **模型名称**: 显示名称，用于界面展示
- **API密钥**: 访问AI服务所需的密钥（本地模型可不填）
- **模型名称**: 具体的模型标识符（如 qwen-plus、gpt-3.5-turbo）
- **最大Token数**: 单次请求的最大token数量（-1表示无限制）
- **温度**: 控制回答的随机性（0-2，数值越大越随机）
- **API地址**: AI服务的API地址

### 使用建议

- 建议配置多个模型以便切换使用
- 本地模型适合离线环境，云端模型功能更强大
- 注意API密钥的安全性，不要泄露给他人
`)

// 方法
const loadModels = async () => {
  try {
    const response = await getAIModels()
    models.value = response as unknown as any[]
  } catch (error) {
    console.error('加载模型列表失败:', error)
    alert('加载模型列表失败')
  }
}

const setCurrentModel = async (modelKey: string) => {
  try {
    await setCurrentAIModel(modelKey)
    await loadModels() // 重新加载以更新状态
    alert('当前模型设置成功')
  } catch (error) {
    console.error('设置当前模型失败:', error)
    alert('设置当前模型失败')
  }
}

const editModel = async (model: any) => {
  try {
    // 从后端获取完整的模型配置
    const response = await getAIConfig()
    const allModels = (response as any).models || {}
    const fullConfig = allModels[model.key]
    
    if (fullConfig) {
      editingModel.value = { 
        key: model.key,
        ...fullConfig
      }
      showEditDialog.value = true
    } else {
      alert('无法获取模型配置')
    }
  } catch (error) {
    console.error('获取模型配置失败:', error)
    alert('获取模型配置失败')
  }
}

const saveModel = async () => {
  try {
    if (showEditDialog.value) {
      await updateAIModel(editingModel.value.key, editingModel.value)
      alert('模型更新成功')
    } else {
      await addAIModel(editingModel.value.key, editingModel.value)
      alert('模型添加成功')
    }
    closeDialog()
    await loadModels()
  } catch (error) {
    console.error('保存模型失败:', error)
    alert('保存模型失败')
  }
}

const deleteModel = async (modelKey: string) => {
  if (!confirm('确定要删除这个模型吗？')) {
    return
  }
  
  try {
    await deleteAIModel(modelKey)
    await loadModels()
    alert('模型删除成功')
  } catch (error) {
    console.error('删除模型失败:', error)
    alert('删除模型失败')
  }
}

const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  editingModel.value = {
    key: '',
    name: '',
    provider: 'local',
    api_key: '',
    model: '',
    max_tokens: 2000,
    temperature: 0.7,
    base_url: ''
  }
}

const getProviderName = (provider: string) => {
  const providerNames: { [key: string]: string } = {
    'local': '本地LM Studio',
    'qwen': '通义千问',
    'openai': 'OpenAI',
    'claude': 'Claude'
  }
  return providerNames[provider] || provider
}

const renderMarkdown = (text: string) => {
  if (!text) return ''
  try {
    marked.setOptions({
      breaks: true,
      gfm: true
    })
    return marked(text)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return text
  }
}

// 生命周期
onMounted(() => {
  loadModels()
})
</script>

<style scoped>
.ai-config {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.config-header h3 {
  margin: 0;
  color: #333;
}

.help-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.help-content {
  font-size: 14px;
  color: #666;
}

.models-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.model-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.2s;
}

.model-item:hover {
  border-color: #2196f3;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.model-item.current {
  border-color: #2196f3;
  background: #e3f2fd;
}

.model-info {
  flex: 1;
}

.model-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.current-badge {
  background: #2196f3;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: normal;
}

.model-provider {
  color: #666;
  font-size: 14px;
}

.model-actions {
  display: flex;
  gap: 8px;
}

.no-models {
  text-align: center;
  color: #999;
  padding: 40px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
}

.config-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.dialog-content h4 {
  margin: 0 0 20px 0;
  color: #333;
}

.config-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #666;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-primary {
  background: #2196f3;
  color: white;
}

.btn-primary:hover {
  background: #1976d2;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
}

.btn-outline {
  background: transparent;
  color: #2196f3;
  border: 1px solid #2196f3;
}

.btn-outline:hover {
  background: #2196f3;
  color: white;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Markdown样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #333;
}

.markdown-content h1 {
  font-size: 1.3em;
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 8px;
}

.markdown-content h2 {
  font-size: 1.1em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 6px;
}

.markdown-content h3 {
  font-size: 1em;
}

.markdown-content p {
  margin: 8px 0;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.markdown-content strong {
  font-weight: 600;
  color: #333;
}

.markdown-content em {
  font-style: italic;
  color: #666;
}
</style> 